package models

import (
	"github.com/astaxie/beego/orm"
	"errors"

	"encoding/hex"
	"crypto/md5"
	"fmt"
)

type Users struct {
	Id           int64
	Username     string
	Password     string
	Status       string
	Tel          string
	Createtime   string
}
func init() {
	orm.RegisterModel(new(Users))
}

func Strtomd5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	rs := hex.EncodeToString(h.Sum(nil))
	return rs
}

func Pwdhash(str string) string {
	return Strtomd5(str)
}
//check login
func CheckLogin(username string, password string) (user Users, err error) {
	user = GetUserByUsername(username)
	fmt.Println("user.Id ----：",user.Id)
	fmt.Println("user.Password ----：",user.Password)
	if user.Id == 0 {
		fmt.Println("账号错误！！！！")
		return user, errors.New("用户不存在")
	}
	if user.Password != Pwdhash(password) {
		fmt.Println("密码错误！！！！")
		return user, errors.New("密码错误")
	}
	return user, nil
}

func GetUserByUsername(username string) (user Users) {
	user = Users{Username: username}
	o := orm.NewOrm()
	o.Read(&user, "Username")

	return user
}

//更新用户
func UpdateUser(u *Users) (int64, error) {
	o := orm.NewOrm()
	users := new(Users)
	//更改之前必须先指定主键
	users.Id = u.Id
	//要更新的内容
	users.Password = Strtomd5(u.Password)
	fmt.Println("users.Id...........................",users.Id)
	fmt.Println("users.Password ...........................",users.Password )
	//更新的ORM格式o.Update(news,"Status","Createtime")
	num, err := o.Update(users, "Password")
	return num, err

}